<template>
  <div>
    <el-form ref="deptForm" label-width="120px">
      <el-form-item label="部门名称">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option
            v-for="item in employee"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import { addDepartment, getDepartmentById, updateDepartment } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      // 这个数用来接收数据回填和交互的
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      employee: [] // 下拉员工信息
    }
  },
  created() {
    this.loadEmployee()
    this.loadDetail()
  },
  methods: {
    // 编辑部门
    async loadDetail() {
      try {
        if (this.isEdit) {
          console.log(this.id)
          const res = await getDepartmentById(this.id)
          console.log('编辑部门', res)
          console.log('根据id获取部门用于修改')
          // console.log('000', this.id)

          this.form = res.data
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 点击确定，编辑部门
    async doEdit() {
      // console.log(this.form.id, 'form------------------------')
      const res = await updateDepartment(this.form)
      console.log('bianji', res)
      // this.form = res.data
      // 告诉父组件，关闭弹窗，更新数据
      this.$emit('success')
    },
    // 新增子部门 /发请求需要id
    async doAdd() {
      const params = { ...this.form, pid: this.id }
      // console.log(this.id)
      // 把需要传的数据解构组合
      const res = await addDepartment(params)
      console.log('新增的子部门', res)
      // 告诉父组件，关闭弹窗，更新数据
      this.$emit('success')
    },
    // 获取下拉员工数据
    async loadEmployee() {
      const res = await getEmployeeSimple()
      // console.log('获取下拉数据', res)
      this.employee = res.data
    },
    // 确定
    hSubmit() {
      // 调用新增的请求
      this.isEdit ? this.doEdit() : this.doAdd()
    },
    // 取消
    hCancel() {
      this.$emit('close')
    }
  }
}
</script>

<style>

</style>
